package org.shiki.hrm.service.impl;

import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.shiki.hrm.domain.VipUser;
import org.shiki.hrm.dto.SmsDto;
import org.shiki.hrm.mapper.VipUserMapper;
import org.shiki.hrm.service.IVerifyCodeService;
import org.shiki.hrm.service.IVipUserService;
import org.shiki.hrm.util.AjaxResult;
import org.shiki.hrm.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private VipUserMapper vipUserMapper;

	@Override
	public AjaxResult createCode(String key) throws IOException {
		// 生成验证码
		String code = VerifyCodeUtils.generateVerifyCode(4);
		// 保存到redis中,设置过期时间为3分钟
		redisTemplate.opsForValue().set(key, code, 3L, TimeUnit.MINUTES);
		// 生成图片
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		VerifyCodeUtils.outputImage(100, 40, bos, code);
		// 使用base64加密为字符,返回给前端
		BASE64Encoder encoder = new BASE64Encoder();
		String imgCode = encoder.encode(bos.toByteArray());
		return AjaxResult.me().setResultObj(imgCode);
	}

	@Override
	public AjaxResult sendSmsCode(SmsDto dto) {
		// 判断用户手机号是否已注册
		String mobile = dto.getMobile();
		VipUser vipUser = new VipUser();
		vipUser.setPhone(mobile);
		VipUser user = vipUserMapper.selectOne(vipUser);
		Assert.isNull(user, "该手机号已注册!");
		// 校验图片验证码
		Object o = redisTemplate.opsForValue().get(dto.getImageCodeKey());
		Assert.notNull(o, "图片验证码无效!");
		Assert.isTrue(dto.getImageCode().equalsIgnoreCase(o.toString()), "验证码输入有误!");
		// 发送短信验证码
		String smsCode = VerifyCodeUtils.generateVerifyCode(6, "0123456789");
		System.out.println(smsCode);
		// 存入redis,设置过期时间为5分钟
		redisTemplate.opsForValue().set("USER-REG" + dto.getMobile(), smsCode, 5L, TimeUnit.MINUTES);
		return AjaxResult.me();
	}
}
